import { getWsPreUrl } from "@/utils/utils";
import _ from "lodash";
import { useEffect, useRef, useState } from "react";

interface IUseWebSocketProps {
  taskId: string
}

const getScoket = (taskId: string, setSocketData: Function) => {
  const str = `${getWsPreUrl()}/supWs?taskId=${taskId}`;
  console.log("str", str);

  let socket = new WebSocket(str);

  let errorTime = 10;

  socket.onopen = () => {
    console.log('连接成功');
  };

  socket.onmessage = _.throttle((event) => {
    // console.log('event.data', event.data);

    if (event.data === "pong") {
      errorTime--;
      if (errorTime < 0) {
        socket.close();
        socket = new WebSocket(str);
      }
    }

    if (!(event.data as string).includes('{')) {
      console.error('socketError:', event.data);
      return;
    }

    if (event.data === '{}') {
      return;
    }

    const data = JSON.parse(event.data);
    errorTime = 10;
    setSocketData(data);
  }, 3000);

  socket.onerror = () => {
    socket.close();
    socket = getScoket(taskId, setSocketData);
  };

  // 连接关闭时触发
  socket.onclose = function (event) {
    console.log('WebSocket connection closed.');
    console.log('Close event code:', event.code);
    console.log('Close event reason:', event.reason);
    console.log('Was clean close:', event.wasClean);
  };

  return socket;
};

const useWebSocket = (props: IUseWebSocketProps) => {
  const [socketData, setSocketData] = useState<any | undefined>(undefined);
  let timeRef = useRef(3);

  useEffect(() => {
    let socket = getScoket(props.taskId, setSocketData);

    const intervalId = setInterval(() => {
      if (socket.readyState === 1) {
        socket.send('ping');
      } else {
        console.dir(socket);
        console.log('socket Status:', socket.readyState);
        // message.error("当前连接异常，重连中"); // 后端暂时无法处理，隐藏提示
        socket.close();
        // clearInterval(intervalId);
        if (timeRef.current > 0) {
          timeRef.current = timeRef.current - 1;
        }
      }
    }, 10000);

    const intervalID2 = setInterval(() => {
      socket.close();
      socket = getScoket(props.taskId, setSocketData);
    }, 1000 * 60 * 10);
    // }, 1000 * 30);

    return () => {
      clearInterval(intervalId);
      clearInterval(intervalID2);
      socket.close();
    };
  }, []);

  return {
    socketData
  };
};

export default useWebSocket;